<?php

namespace App\Http\Controllers\Api;

use Illuminate\Support\Facades\DB;
use App\V3\V3_1\Models\MaterielClassModel;
use App\Http\Controllers\Controller;
use App\V3\V3_1\Models\PackageContentModel;
use App\Services\PackageService;
use App\V3\V3_1\Models\PackageModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class PackageController extends BaseController
{
    /**
     * @套餐列表
     * created 在 2021/11/02 14:44 创建
     * @author SunWu
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
    */
    public function list(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'pageSize' =>'required|integer',//页面大小
            'currentPage' =>'required|integer',//当前页
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        $keyword = empty($data['keyword'])?'':$data['keyword'];

        if($keyword != '') {
            $result = SELF::withSearch($keyword, $data);
        }
        else {
            $result = SELF::withoutSearch($keyword, $data);
        }

        return $this->success($result);
    }

    private function withoutSearch($keyword, $data)
    {
        return PackageModel::select(
                                'id',
                                'package_name',
                                'status'
                            )
                            ->where('main_id', $this->getMainUserId())
                            ->where('delete_flag', 0)
                            ->with('hasManyContent', function($query) use ($keyword) {
                                $query->select(
                                        'package_content.id',
                                        'materiel_first_class_id',
                                        'a.class_name as materiel_first_class_name',
                                        'a.class_no as materiel_first_class_no',
                                        'package_content.materiel_class_id',
                                        'b.class_name as materiel_class_name',
                                        'b.class_no as materiel_class_no',
                                        'd.materiel_name',
                                        'd.type_name',
                                        'd.materiel_no',
                                        'package_content.storage_id',
                                        'e.storage_name',
                                        'e.storage_address',
                                        'package_id',
                                        'num',
                                        'c.in_storage_num',
                                        'c.id as storage_manage_id',
                                        'c.delete_flag'
                                    )
                                    ->leftJoin('materiel_class as a', 'materiel_first_class_id', '=', 'a.id')
                                    ->leftJoin('materiel_class as b', 'package_content.materiel_class_id', '=', 'b.id')
                                    ->leftJoin('materiel_type as d', 'package_content.type_id', '=', 'd.id')
                                    ->leftJoin('storage as e', 'e.id', '=', 'package_content.storage_id')
                                    ->leftJoin('storage_manage as c', 'c.id', '=', 'storage_manage_id')
                                    ->where('package_content.delete_flag', 0);
                            })
                            ->orderBy('id', 'DESC')
                            ->paginate($data['pageSize'],['*'], '',$data['currentPage']);
    }

    private function withSearch($keyword, $data)
    {
        //检索套餐名称信息
        $packageInfo = PackageModel::select(
                                        'id'
                                    )
                                    ->where('package_name', 'LIKE', '%'.$keyword.'%')
                                    ->where('main_id', $this->getMainUserId())
                                    ->where('delete_flag', 0)->get()->toArray();

        $packageId = [];
        foreach($packageInfo as $v) {
                $packageId[] = $v['id'];
        }

        $packageContentInfo = PackageContentModel::select(
                                    'a.id',
                                    'package_id'
                                )
                                ->from('package_content as a')
                                ->leftJoin('materiel_class as b', 'b.id', '=', 'a.materiel_class_id')
                                ->leftJoin('materiel_class as c', 'c.id', '=', 'b.parent_id')
                                ->leftJoin('package as d', 'd.id', '=', 'a.package_id')
                                ->where(function($query) use ($keyword) {
                                    $query->orWhere('materiel_class_name', 'LIKE', '%'.$keyword.'%');
                                    $query->orWhere('materiel_first_class_name', 'LIKE', '%'.$keyword.'%');
                                    $query->orWhere('materiel_first_class_no', 'LIKE', '%'.$keyword.'%');
                                    $query->orWhere('materiel_class_no', 'LIKE', '%'.$keyword.'%');
                                    $query->orWhere('c.class_name', 'LIKE', '%'.$keyword.'%');
                                    $query->orWhere('c.class_no', 'LIKE', '%'.$keyword.'%');
                                    $query->orWhere('materiel_name', 'LIKE', '%'.$keyword.'%');
                                    $query->orWhere('type_name', 'LIKE', '%'.$keyword.'%');
                                    $query->orWhere('materiel_no', 'LIKE', '%'.$keyword.'%');
                                    $query->orWhere('d.package_name', 'LIKE', '%'.$keyword.'%');
                                })->get()->toArray();

        $packageContentParentId = [];
        foreach($packageContentInfo as $v1) {
            $packageContentParentId[] = $v1['package_id'];
        }

        $arr = array_merge($packageContentParentId, $packageId);

        $query = PackageModel::select(
                                'id',
                                'package_name',
                                'status'
                            )
                            ->where('main_id', $this->getMainUserId())
                            ->where('delete_flag', 0)
                            ->with('hasManyContent', function($query) {
                                $query->select(
                                        'package_content.id',
                                        'materiel_first_class_id',
                                        'a.class_name as materiel_first_class_name',
                                        'a.class_no as materiel_first_class_no',
                                        'package_content.materiel_class_id',
                                        'b.class_name as materiel_class_name',
                                        'b.class_no as materiel_class_no',
                                        'c.materiel_name',
                                        'c.type_name',
                                        'c.materiel_no',
                                        'package_content.storage_id',
                                        'd.storage_name',
                                        'd.storage_address',
                                        'storage_manage_id',
                                        'package_id',
                                        'num',
                                        'e.id as storage_manage_id',
                                        'e.in_storage_num',
                                        'e.delete_flag'
                                    )
                                    ->leftJoin('materiel_class as a', 'materiel_first_class_id', '=', 'a.id')
                                    ->leftJoin('materiel_class as b', 'package_content.materiel_class_id', '=', 'b.id')
                                    ->leftJoin('materiel_type as c', 'package_content.type_id', '=', 'c.id')
                                    ->leftJoin('storage as d', 'd.id', '=', 'package_content.storage_id')
                                    ->leftJoin('storage_manage as e', 'e.id', '=', 'package_content.storage_manage_id')
                                    ->where('package_content.delete_flag', 0);
                            })
                            ->whereIn('id', $arr)
                            ->orderBy('id', 'DESC')
                            ->paginate($data['pageSize'],['*'], '',$data['currentPage']);

                            return $query;
    }

    /**
     * @新建套餐或套餐内容
     * created 在 2021/11/09 10:38 创建
     * @author SunWu
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
    */
    public function add(Request $request)
    {
        $data = $request->all();

        if($data['type']) {
            $result = SELF::addPackage($data);
        }
        else {
            $result = SELF::packageContentAdd($data);
        }

        $this->log('新建套餐或套餐内容', $data);

        return response()->json($result);
    }

    /**
     * @新建套餐
     * created 在 2021/11/02 14:44 创建
     * @author SunWu
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
    */
    public function addPackage($data)
    {
        //参数验证
        $validator = Validator::make($data, [
                'package_name' =>'required',//页面大小
            ],
            [
                'package_name.required' => '请填写套餐名'
            ]
        );

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        return PackageService::add($data, $this->getMainUserId());
    }

    /**
     * @删除套餐或套餐内容
     * created 在 2021/11/02 16:30 创建
     * @author SunWu
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
    */
    public function del(Request $request)
    {
        $data = $request->all();

        if($data['type']) {
            $result = SELF::delPackage($data);
        }
        else {
            $result = SELF::packageContentDel($data);
        }

        return $result;
    }

    /**
     * @删除套餐
     * created 在 2021/11/02 16:30 创建
     * @author SunWu
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
    */
    public function delPackage($data)
    {
        if(empty($data)) {
            return $this->fail('', '参数`套餐id`缺失');
        }

//        if(!SELF::checkPackageStatus($data['id'])) {
//            return ['code' => 1, 'msg' => '该套操已使用无法进行修改删除添加等操作', 'data' => ''];
//        }

        PackageModel::where('id', $data['id'])->update(['delete_flag' => 1]);

        $this->log('删除套餐', $data);
        return $this->success();
    }

    public function checkPackageStatus($packageId)
    {
        $checkPackageInfo = PackageModel::where('id', $packageId)->first();

        if(!$checkPackageInfo['status']) {
            return false;
        }
        else {
            return true;
        }
    }

    /**
     * @修改套餐或套餐内容
     * created 在 2021/11/02 16:40 创建
     * @author SunWu
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
    */
    public function edit(Request $request)
    {
        $data = $request->all();

        if($data['type']) {
            unset($data['type']);
            $result = SELF::editPackage($data);
        }
        else {
            unset($data['type']);
            $result = SELF::packageContentEdit($data);
        }

        return $result;
    }

    /**
     * @修改套餐
     * created 在 2021/11/02 16:40 创建
     * @author SunWu
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
    */
   public function editPackage($data)
   {
        //参数验证
        $validator = Validator::make($data, [
                'id' =>'required|integer',//页面大小
                'package_name' =>'required',//当前页
            ],
            [
                'id.required' => '参数`套餐id`缺失',
                'id.integer' => '参数`套餐id`只能为数字',
                'package_name.required' => '参数`套餐名称`缺失',
            ]
        );

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

       if(!SELF::checkPackageStatus($data['id'])) {
           return $this->fail('', '该套操已使用无法进行修改删除添加等操作');
       }

        $result = PackageService::edit($data, $this->getMainUserId());

        if($result['code']) {
            return $this->fail('', $result['msg']);
        }
        else {
            $this->log('修改套餐', $data);
            return $this->success();
        }
    }

    /**
     * @添加套餐内容
     * created 在 2021/11/04 15:01 创建
     * @author SunWu
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
    */
    public function packageContentAdd($data)
    {
        //参数验证
        $validator = Validator::make($data, [
                'id' =>'required|integer',//套餐id
                'storage_manage_id' =>'required',//库存id
                'num' =>'required|numeric|min:0',//套餐内容数量
            ],
            [
                'id.required' => '参数`套餐id`缺失',
                'id.integer' => '参数`套餐id`只能为数字',
                'storage_manage_id.integer' => '参数`库存id`只能为数字',
                'storage_manage_id.required' => '参数`库存id`缺失',
                'num.required' => '参数`套餐内物料数量`缺失',
                'num.numeric' => '参数`套餐内物料数量`只能为数字',
                'num.min' => '参数`套餐内物料数量`必须大于或等于0',
            ]
        );

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        $result = PackageService::packageContentAdd($this->getMainUserId(), $data);
        return $result;
    }

    /**
     * @修改套餐内容
     * created 在 2021/11/04 15:01 创建
     * @author SunWu
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
    */
   public function packageContentEdit($data)
   {
       //参数验证
       $validator = Validator::make($data, [
               'id' =>'required|integer',//套餐内容id
               'storage_manage_id' =>'required|integer',//库存id
               'storage_id' =>'required|integer',//仓库id
               'storage_name' =>'required',//仓库名
               'storage_address' =>'required',//仓库地址
               'package_id' =>'required|integer',//套餐id
               'num' =>'required|numeric|min:0',//套餐内容数量
           ],
           [
               'id.required' => '参数`套餐内容id`缺失',
               'id.integer' => '参数`套餐内容id`只能为数字',
               'package_id.required' => '参数`套餐id`缺失',
               'package_id.integer' => '参数`套餐id`只能为数字',
               'storage_manage_id.integer' => '参数`库存id`只能为数字',
               'storage_manage_id.required' => '参数`库存id`缺失',
               'storage_id.integer' => '参数`仓库id`只能为数字',
               'storage_id.required' => '参数`仓库id`缺失',
               'num.required' => '参数`套餐内物料数量`缺失',
               'num.numeric' => '参数`套餐内物料数量`只能为数字',
               'num.min' => '参数`套餐内物料数量`必须大于或等于0',
               'storage_name.required' => '参数`仓库名`缺失',
               'storage_address.required' => '参数`仓库地址`缺失',
           ]
       );

       //参数错误响应
       if ($info = $validator->errors()->first()) {
           return response()->json([
               'code' => 1,
               'msg' => $info,
               'data' => '',
           ]);
       }

       $materielContentInfo = PackageContentModel::where('id', $data['id'])->first();

       if(!SELF::checkPackageStatus($materielContentInfo['package_id'])) {
           return $this->fail('', '该套操已使用无法进行修改删除添加等操作');
       }

       $result = PackageService::packageContentEdit($data, $this->getMainUserId());

       if($result['code']) {
           return $this->fail('', $result['msg']);
       }
       else {
           $this->log('修改套餐内容', $data);
           return $this->success();
       }
   }

   /**
    * @指定套餐内容对应的在库信息列表(修改套餐内容用)
    * created 在 2021/11/04 15:32 创建
    * @author SunWu
    * @param Request $request
    * @return \Illuminate\Http\JsonResponse
   */
   public function packageStorageList(Request $request)
   {
       //参数验证
       $validator = Validator::make($data = $request->all(), [
               'id' =>'required|integer',//套餐内容id
           ],
           [
               'id.required' => '参数`套餐内容id`缺失',
               'id.integer' => '参数`套餐内容id`只能为数字',
           ]
       );

       //参数错误响应
       if ($info = $validator->errors()->first()) {
           return response()->json([
               'code' => 1,
               'msg' => $info,
               'data' => '',
           ]);
       }

       return $this->success(
           PackageService::packageStorageList($this->getMainUserId(), $data)
       );
   }

   /**
    * @删除指定套餐内容
    * created 在 2021/11/04 16:23 创建
    * @author SunWu
    * @param Request $request
    * @return \Illuminate\Http\JsonResponse
   */
   public function packageContentDel($data)
   {
       //参数验证
       $validator = Validator::make($data, [
               'id' =>'required|integer',//套餐内容id
           ],
           [
               'id.required' => '参数`套餐内容id`缺失',
               'id.integer' => '参数`套餐内容id`只能为数字',
           ]
       );

       //参数错误响应
       if ($info = $validator->errors()->first()) {
           return response()->json([
               'code' => 1,
               'msg' => $info,
               'data' => '',
           ]);
       }

       $materielContentInfo = PackageContentModel::where('id', $data['id'])->first();

       if(!SELF::checkPackageStatus($materielContentInfo['package_id'])) {
           return $this->fail('', '该套操已使用无法进行修改删除添加等操作');
       }

       PackageContentModel::where('id', $data['id'])->update(['delete_flag' => 1]);

       $this->log('删除套餐内容', $data);
       return $this->success();
   }

   /**
    * @添加套餐内容-可用库存物料信息
    * created 在 2021/11/04 16:23 创建
    * @author SunWu
    * @param Request $request
    * @return \Illuminate\Http\JsonResponse
   */
   public function packageContentSelect(Request $request)
   {
       //参数验证
       $validator = Validator::make($data = $request->all(), [
               'id' =>'required|integer',//套餐id
           ],
           [
               'id.required' => '参数`套餐id`缺失',
               'id.integer' => '参数`套餐id`只能为数字',
           ]
       );

       //参数错误响应
       if ($info = $validator->errors()->first()) {
           return response()->json([
               'code' => 1,
               'msg' => $info,
               'data' => '',
           ]);
       }

       return $this->success(PackageService::packageContentSelect($this->getMainUserId(), $data));
   }

   /**
    * @套餐内容列表
    * created 在 2021/11/20 09:44 创建
    * @author SunWu
    * @param Request $request
    * @return \Illuminate\Http\JsonResponse
   */
   public function contentList(Request $request)
   {
       //参数验证
       $validator = Validator::make($data = $request->all(), [
               'id' =>'required|integer',//套餐id
               'pageSize' =>'required|integer',//页面大小
               'currentPage' =>'required|integer',//当前页
           ],
           [
               'id.required' => '参数`套餐id`缺失',
               'id.integer' => '参数`套餐id`只能为数字',
           ]
       );

       //参数错误响应
       if ($info = $validator->errors()->first()) {
           return response()->json([
               'code' => 1,
               'msg' => $info,
               'data' => '',
           ]);
       }

       return $this->success(PackageService::contentList($data));
   }

    /**
     * @套餐出库
     * @created 在 2021/12/2 16:36 创建
     * @param Request $request
     * @author: Sun Wu
     */
   public function packageOut(Request $request)
   {
       //参数验证
       $validator = Validator::make($data = $request->all(), [
           'id' =>'required|integer',//套餐id
           'num' =>'required|integer',//套餐数量
       ],
           [
               'id.required' => '参数`套餐id`缺失',
               'id.integer' => '参数`套餐id`只能为数字',
           ]
       );

       //参数错误响应
       if ($info = $validator->errors()->first()) {
           return response()->json([
               'code' => 1,
               'msg' => $info,
               'data' => '',
           ]);
       }

       $data['user_id'] = $this->getUserId();
       $data['main_id'] = $this->getMainUserId();

       return response()->json(
           PackageService::packageOut($data)
       );
   }
}
